<template>
  <div class="detail-page">
    <el-card class="page-header">
      <div class="header-content">
        <el-button @click="goBack" type="primary" plain>
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
        <h2>{{ pageTitle }}</h2>
      </div>
    </el-card>

    <el-card class="tab-container">
      <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="tab in tabs"
          :key="tab.name"
          :label="tab.label"
          :name="tab.name"
          :closable="tab.closable"
        >
          <component
            :is="tab.component"
            :data="tab.data"
            :type="tab.type"
            @save="handleSave"
            @close="handleCloseTab"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ArrowLeft } from '@element-plus/icons-vue'
import UserDetail from '../components/UserDetail.vue'
import ProductDetail from '../components/ProductDetail.vue'
import OrderDetail from '../components/OrderDetail.vue'
import ConfigAppDetail from '../components/ConfigAppDetail.vue'

export default {
  name: 'DetailPage',
  components: {
    ArrowLeft,
    UserDetail,
    ProductDetail,
    OrderDetail,
    ConfigAppDetail
  },
  data() {
    return {
      activeTab: '',
      tabs: [],
      pageTitle: '详情页面'
    }
  },
  mounted() {
    this.initializeTabs()
  },
  methods: {
    initializeTabs() {
      const { type, id, action } = this.$route.query
      
      if (type && id) {
        this.addTab(type, id, action || 'view')
      }
    },
    
    addTab(type, id, action = 'view') {
      const tabId = `${type}-${id}-${action}`
      
      // 检查是否已存在相同的tab
      const existingTab = this.tabs.find(tab => tab.name === tabId)
      if (existingTab) {
        this.activeTab = tabId
        return
      }
      
      let component, label, data
      
      switch (type) {
        case 'user':
          component = 'UserDetail'
          label = action === 'edit' ? '编辑用户' : '用户详情'
          data = this.getUserData(id)
          this.pageTitle = '用户管理'
          break
        case 'product':
          component = 'ProductDetail'
          label = action === 'edit' ? '编辑商品' : '商品详情'
          data = this.getProductData(id)
          this.pageTitle = '商品管理'
          break
        case 'order':
          component = 'OrderDetail'
          label = action === 'edit' ? '编辑订单' : '订单详情'
          data = this.getOrderData(id)
          this.pageTitle = '订单管理'
          break
        case 'configApp':
          component = 'ConfigAppDetail'
          label = action === 'edit' ? '编辑应用' : '应用详情'
          data = this.getConfigAppData(id)
          this.pageTitle = '配置中心应用管理'
          break
        default:
          return
      }
      
      const newTab = {
        name: tabId,
        label: `${label} (ID: ${id})`,
        component,
        data,
        type: action,
        closable: true
      }
      
      this.tabs.push(newTab)
      this.activeTab = tabId
    },
    
    getUserData(id) {
      // 模拟获取用户数据
      return {
        id: id,
        username: `用户${id}`,
        email: `user${id}@example.com`,
        phone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
        role: Math.random() > 0.5 ? 'admin' : 'user',
        status: Math.random() > 0.2 ? 1 : 0,
        createTime: new Date().toLocaleString()
      }
    },
    
    getProductData(id) {
      // 模拟获取商品数据
      const categories = ['电子产品', '服装', '食品', '图书', '家居', '运动', '美妆', '汽车']
      return {
        id: id,
        name: `商品${id}`,
        category: categories[Math.floor(Math.random() * categories.length)],
        price: (Math.random() * 1000 + 10).toFixed(2),
        stock: Math.floor(Math.random() * 1000),
        description: `这是商品${id}的详细描述`,
        status: Math.random() > 0.2 ? 1 : 0,
        createTime: new Date().toLocaleString()
      }
    },
    
    getOrderData(id) {
      // 模拟获取订单数据
      const statuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled']
      const paymentMethods = ['alipay', 'wechat', 'bank', 'cash']
      return {
        id: id,
        orderNo: `ORD${String(id).padStart(8, '0')}`,
        customerName: `客户${id}`,
        customerPhone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
        totalAmount: (Math.random() * 1000 + 50).toFixed(2),
        status: statuses[Math.floor(Math.random() * statuses.length)],
        paymentMethod: paymentMethods[Math.floor(Math.random() * paymentMethods.length)],
        createTime: new Date().toLocaleString()
      }
    },
    
    getConfigAppData(id) {
      // 模拟获取配置应用数据
      const statuses = ['active', 'inactive', 'pending']
      return {
        id: id,
        appName: `应用${id}`,
        remark: `这是应用${id}的备注信息`,
        status: statuses[Math.floor(Math.random() * statuses.length)],
        createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toLocaleString(),
        updateTime: new Date().toLocaleString()
      }
    },
    
    handleTabClick(tab) {
      this.activeTab = tab.name
    },
    
    handleCloseTab(tabName) {
      const index = this.tabs.findIndex(tab => tab.name === tabName)
      if (index > -1) {
        this.tabs.splice(index, 1)
        
        // 如果关闭的是当前激活的tab，切换到其他tab
        if (this.activeTab === tabName) {
          if (this.tabs.length > 0) {
            this.activeTab = this.tabs[Math.max(0, index - 1)].name
          } else {
            this.goBack()
          }
        }
      }
    },
    
    handleSave(data) {
      console.log('保存数据:', data)
      // 这里可以调用API保存数据
    },
    
    goBack() {
      this.$router.go(-1)
    },
    
    // 公开方法，供外部调用添加新tab
    openTab(type, id, action = 'view') {
      this.addTab(type, id, action)
    }
  },
  
  // 监听路由变化，支持通过URL直接打开tab
  watch: {
    '$route.query': {
      handler(newQuery) {
        const { type, id, action } = newQuery
        if (type && id) {
          this.addTab(type, id, action || 'view')
        }
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.detail-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-content h2 {
  margin: 0;
  color: #409eff;
}

.tab-container {
  min-height: 600px;
}

.el-tabs {
  height: 100%;
}

.el-tab-pane {
  padding: 20px;
}
</style>